<template>
  <div>
    <el-upload
      v-if="!isShowProgress"
      class="avatar-uploader"
      action="#"
      :file-list="fileList"
      :on-preview="OnPreview"
      :on-remove="OnRemove"
      :http-request="OnRequest"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :limit="limit"
      :on-exceed="onExceed"
      accept="image/png,image/jpeg"
      list-type="picture-card"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <el-dialog
      title="头像"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imgUrl">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDJRItDG2XrugBPM2RbU6RWKr64mDMFsEJ',
  SecretKey: 'pcARRAcngIejX3IHzQaU7SWKr75mDMEp'
})
console.log(cos)
export default {
  name: 'UploadImg',
  props: {
    limit: {
      type: Number,
      default: () => 0
    }
  },
  data() {
    return {
      isShowProgress: false, // 进度条是否显示
      imgUrl: '',
      dialogVisible: false,
      fileList: [],
      percentage: 0// 进度条
    }
  },

  created() {

  },

  methods: {
    // 上传图片
    OnRequest(data) {
      console.log(data)
      this.isShowProgress = true
      // 上传图片至存储桶
      cos.putObject({
        Bucket: 'hrsaas-1308960738', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = Math.floor(progressData.percent * 100)
          // if (progressData.percent === 1) {
          //   this.percentage = 100
          //   this.isShowProgress = false
          // }
        }
      }, (err, data) => {
        console.log(err || data)
        if (err) {
          this.isShowProgress = false
          this.$message.error('网络错误,上传失败')
          this.fileList.splice(this.fileList.length - 1, 1)
        }
        if (!err && data.statusCode === 200) {
          console.log('上传图片成功')
          console.log(data)
          this.isShowProgress = false
          const imgUrl = this.fileList.length - 1
          this.fileList[imgUrl].url = 'https://' + data.Location
          this.$emit('on-success', this.fileList)
        }
      })
    },
    // 预览图片
    OnPreview(file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 删除图片
    OnRemove(file, fileList) {
      this.fileList = fileList
    },
    // 图片上传之前
    beforeUpload(file) {
      const maxSize = 4 * 1024 * 1024
      const imgType = ['image/png', 'image/jpeg']
      if (!imgType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('图片大小最大为4MB')
        return false
      }
    },
    // 上传
    onChange(file, fileList) {
      // console.log(fileList)
      this.fileList = fileList
    },
    // 上传文件数量超出限制
    onExceed() {
      this.$message.error('最多只能上传' + this.limit + '张图片')
    }
  }
}
</script>

<style lang='scss'>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
</style>
